from django.core.mail import send_mail
from random import Random
from eduOnline.settings import EMAIL_FROM, EMAIL_URL
from users.models import EmailVerifyRecord


def send_an_email(email, send_type='register'):
    email_record = EmailVerifyRecord()
    email_record.code = generate_code()
    email_record.send_type = send_type
    email_record.email = email
    email_record.save()

    email_title = ''
    email_body = ''

    if send_type == 'register':
        email_title = "慕学在线网注册激活链接"
        email_body = "请点击下面的链接激活你的账号: {}{}/{}".format(EMAIL_URL, 'active', email_record.code)
        status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if status:
            pass

    elif send_type == 'forget':
        email_title = "慕学在线网注册密码重置链接"
        email_body = "请点击下面的链接重置密码: {}{}/{}".format(EMAIL_URL, 'reset', email_record.code)
        status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if status:
            pass

    elif send_type == 'update_email':
        email_title = "慕学在线邮箱修改验证码"
        email_body = "你的邮箱验证码为: {}{}/{}".format(EMAIL_URL, 'update', email_record.code)
        status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if status:
            pass


def generate_code(code_length=8):
    code = ''
    char = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    random = Random()
    length = len(char) - 1
    for i in range(code_length):
        code += char[random.randint(0, length)]
    return code
